package com.example.youyouhaodian.service.impl;

import com.example.youyouhaodian.dao.SeckillgoodsDao;
import com.example.youyouhaodian.pojo.Seclillgoods;
import com.example.youyouhaodian.service.SeckillgoodsService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


//秒杀商品
@Service
public class SeckillgoodsServiceImpl  implements SeckillgoodsService {


    @Autowired
    SeckillgoodsDao seckillgoodsDao;
    @Autowired
    RedisTemplate redisTemplate;

    //系统初始化将秒杀商品静态资源写入redis,并设置有效时间
    public void set() {
        String goodskey;
        Object value;
        long expireTime;

        java.sql.Timestamp date1=null;
        java.sql.Timestamp date2=null;
        java.util.Date d=null;
        java.util.Date b=null;

        long count;//创建库存表value
        String k="k";
        String countkey;



        //遍历数据库秒杀商品信息
        List<Seclillgoods> list = seckillgoodsDao.slectScegoods();
        for (Seclillgoods SD : list) {

            if (SD.getSeckillGoodsId() != 0) {
                goodskey = String.valueOf(SD.getSeckillGoodsId());


                StringBuffer str = new StringBuffer();
                str.append(k);
                str.append(goodskey);
                count=SD.getStockCount();
                countkey=str.toString();




                value = SD;
                //时间类型转换成long

                date1 = SD.getStartTime();
                date2 = SD.getEndTime();
                d = new java.util.Date(date1.getTime());
                b = new java.util.Date(date2.getTime());
                System.out.println("转化：" + d.getTime());
                System.out.println("转化：" + b.getTime());
                expireTime = b.getTime() - d.getTime();
                System.out.println("以秒计的时间差：" + expireTime);

                //写入缓冲
                try {
                    //创建商品详情表

                    ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
                    redisTemplate.opsForSet().add(goodskey, value);
                    redisTemplate.expire(goodskey, expireTime, TimeUnit.MILLISECONDS);
                    //创建库存表
                    operations.set(countkey, count);
                    redisTemplate.expire(countkey, expireTime, TimeUnit.MILLISECONDS);
                    System.out.println("库存KEY：" + countkey+"库存V"+count+"库存时间"+expireTime);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //查询全部秒杀商品，判断时间


    //访问单个秒杀商品详细信息
    public Set<Seclillgoods> goods(String goodsid){
        //通过秒杀商品id,查询秒杀商品
        String key=goodsid;
        Set<Seclillgoods> SET=redisTemplate.opsForSet().members(key);
        for(Seclillgoods SD: SET){
            System.out.println(SD.getSeckillGoodsId());
            System.out.println(SD.getGoods_Name());
            System.out.println(SD.getGoods_Title());
            System.out.println(SD.getGoods_Img());
            System.out.println(SD.getGoods_Detail());
            System.out.println(SD.getMiaoshaPrice());
            System.out.println(SD.getStockCount());
            System.out.println(SD.getGoods_Comment());
            System.out.println(SD.getGoods_Volume());
            System.out.println(SD.getStartTime());
            System.out.println(SD.getEndTime());

        }
         return  SET;
    }


    //开始秒杀
    public  String secgoods(String goodsid){
        //取消判断用户名是否登录
        //判断商品是否存在
        //判断该用户是否购买一次
        //判断商品库存是否大于零
        //生成临时订单，并设置有效时间

        String key="3";//从消息队列获取商品id
        String key2="5";//用户id

        //=======================
        String goodskey;
        String k="k";//k库存
        String s="s";//订单
        long oldcount=0;//原库存
        long count=0;//-1后库存
        long expireTime;//订单有效期

        StringBuffer str = new StringBuffer();//生成查找库存的key
        str.append(k);
        str.append(key);
        goodskey=str.toString();


        StringBuffer str2 = new StringBuffer();//生成订单key
        str2.append(s);
        str2.append(key2);


        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();


        if(String.valueOf(operations.get(goodskey)).equals("null")){//秒杀商品为空
            System.out.println("商品已下架");
        }else if(redisTemplate.hasKey(str2.toString())) {//商品存在=====判断是否存在该用户订单
            System.out.println("您没机会了！一会儿再来吧");
        }else if(!redisTemplate.hasKey(str2.toString())){//没有该用户订单可以抢购
            oldcount= Long.valueOf(String.valueOf(operations.get(goodskey)));
            System.out.println("原库存："+oldcount);
            if(oldcount>0){

                count=oldcount-1;//库存减一

                try {
                    operations.getAndSet(goodskey, count);//写入redis
                }catch (Exception E){
                    System.out.println("商品已下架");

                }finally {
                    System.out.println("商品已下架");
                }
                StringBuilder value = new StringBuilder();//生成订单编号(用户编号拼接K+随机数)
                String rm = RandomStringUtils.randomNumeric(6 - 1);
                value.append(key2);
                value.append(rm);


                expireTime=120000;
                operations.set(str2.toString(),value);
                redisTemplate.expire(str2.toString(), expireTime, TimeUnit.MILLISECONDS);//生成临时订单,两分钟失效

                System.out.println("商品现库存:" + count);
                System.out.println("订单号:" + value);

            }else{
                System.out.println("呵呵!被抢光了");
            }
        }
        return "排队成功";
    }



    //前台轮询秒杀情况,成功跳转购物车，失败返回结果




    //查看购物车，超时2分钟未付款，自动取消订单/已付款写入数据库





    //查看订单

}